﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using Silverlight;
using System.Text.RegularExpressions;

namespace SalaryChannel
{
    public class Xml2Table
    {
        private static Regex colRegex = new Regex(@"^\<(?<column>.+)\>(?<value>.*)\</\k<column>\>$");

        public static Silverlight.DataTable Convert(string TableName, System.Collections.Generic.List<string> Columns, string XmlString)
        {
            Silverlight.DataTable sTable = new DataTable();
            sTable.TableName = TableName;

            string rowHeader = string.Format("<{0}>", sTable.TableName);
            string rowTayler = string.Format("</{0}>", sTable.TableName);

            foreach (string col in Columns)
            {
                sTable.Columns.Add(new DataColumn(col));
            }
            Silverlight.DataRow row = null;
            using (StringReader reader = new StringReader(XmlString))
            {
                try
                {
                    while (true)
                    {
                        string line =string.Empty;
                        try
                        {
                            line = reader.ReadLine();
                        }
                        catch (Exception ex)
                        {
                            
                            throw ex;
                        }
                        if (line == null)
                        {
                            // the end
                            break;
                        }
                        line = line.Trim();
                        if (line == string.Empty
                            || line.Contains("DocumentElement"))
                        {
                            continue;
                        }
                        else if (line.Contains(rowHeader))
                        {
                            row = sTable.NewRow();
                        }
                        else if (line.Contains(rowTayler))
                        {
                            sTable.Rows.Add(row);
                        }
                        else
                        {
                            if (colRegex.IsMatch(line))
                            {
                                string column = colRegex.Match(line).Result("${column}");
                                string value = colRegex.Match(line).Result("${value}");
                                row[column] = value;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    
                    throw ex;
                }
            }


            return sTable;
        }
    }
}
